<!DOCTYPE html>






<html class="theme-next muse use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">







  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">


















  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">



















































<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.3" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.3">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.3" color="#222">





  <meta name="keywords" content="JVM,">










<meta name="description" content="前面介绍了类加载器的实现，目前我们已经可以加载普通的类，并创建该类的对象了，但是目前我们的 JVM 还不支持数组。数组类虽然也是类，但是其加载方式和之前所讲的通过 class 文件的形式加载是完全不同的，本节将介绍 JVM 中数组的实现，并完善我们的类加载器，使其可以加载数组。">
<meta name="keywords" content="JVM">
<meta property="og:type" content="article">
<meta property="og:title" content="手写JVM系列(14)-数组的实现">
<meta property="og:url" content="https://zachaxy.github.io/2018/01/12/手写JVM系列-14-数组的实现/index.html">
<meta property="og:site_name" content="zachaxy">
<meta property="og:description" content="前面介绍了类加载器的实现，目前我们已经可以加载普通的类，并创建该类的对象了，但是目前我们的 JVM 还不支持数组。数组类虽然也是类，但是其加载方式和之前所讲的通过 class 文件的形式加载是完全不同的，本节将介绍 JVM 中数组的实现，并完善我们的类加载器，使其可以加载数组。">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2019-09-01T11:13:24.303Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="手写JVM系列(14)-数组的实现">
<meta name="twitter:description" content="前面介绍了类加载器的实现，目前我们已经可以加载普通的类，并创建该类的对象了，但是目前我们的 JVM 还不支持数组。数组类虽然也是类，但是其加载方式和之前所讲的通过 class 文件的形式加载是完全不同的，本节将介绍 JVM 中数组的实现，并完善我们的类加载器，使其可以加载数组。">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Muse',
    version: '5.1.3',
    sidebar: {"position":"right","display":"hide","offset":12,"b2t":false,"scrollpercent":true,"onmobile":true},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: 'undefined',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://zachaxy.github.io/2018/01/12/手写JVM系列-14-数组的实现/">





  <title>手写JVM系列(14)-数组的实现 | zachaxy</title>









</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">






  <div class="container sidebar-position-right page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">


    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">zachaxy</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>

        <h1 class="site-subtitle" itemprop="description">纵情向前！</h1>

  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">



    <ul id="menu" class="menu">


        <li class="menu-item menu-item-home">
          <a href="/" rel="section">

              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>

            首页
          </a>
        </li>


        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">

              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>

            标签
          </a>
        </li>


        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">

              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>

            归档
          </a>
        </li>


        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">

              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>

            关于
          </a>
        </li>



        <li class="menu-item menu-item-search">

            <a href="javascript:;" class="popup-trigger">


              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>

            搜索
          </a>
        </li>

    </ul>



    <div class="site-search">

  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>

</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">


  <div id="posts" class="posts-expand">








  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">



  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://zachaxy.github.io/2018/01/12/手写JVM系列-14-数组的实现/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="zachaxy">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="zachaxy">
    </span>


      <header class="post-header">



          <h2 class="post-title" itemprop="name headline">手写JVM系列(14)-数组的实现</h2>


        <div class="post-meta">
          <span class="post-time">

              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>

                <span class="post-meta-item-text">发表于</span>

              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-01-12T19:18:25+08:00">
                2018-01-12
              </time>





          </span>













            <div class="post-wordcount">


                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>

                  <span class="post-meta-item-text">字数统计&#58;</span>

                <span title="字数统计">
                  3,018
                </span>





            </div>




        </div>
      </header>





    <div class="post-body" itemprop="articleBody">





        <p>前面介绍了<a href="https://zachaxy.github.io/2018/01/04/%E6%89%8B%E5%86%99JVM%E7%B3%BB%E5%88%97-12-%E7%B1%BB%E5%8A%A0%E8%BD%BD%E5%99%A8%E7%9A%84%E5%AE%9E%E7%8E%B0/">类加载器的实现</a>，目前我们已经可以加载普通的类，并创建该类的对象了，但是目前我们的 JVM 还不支持数组。数组类虽然也是类，但是其加载方式和之前所讲的通过 class 文件的形式加载是完全不同的，本节将介绍 JVM 中数组的实现，并完善我们的类加载器，使其可以加载数组。</p>
<a id="more"></a>

<h1 id="数组概述"><a href="#数组概述" class="headerlink" title="数组概述"></a>数组概述</h1><ul>
<li>基本数组类型：数组中的元素类型是基本类型</li>
<li>引用数组类型：数组中的元素类型是引用类型</li>
</ul>
<p>数组类也是类，其父类同样也是 Object，但是其又和普通的类有一些差异：</p>
<ul>
<li>普通的类从 class 文件中加载,而数组类则是 JVM 在运行时生成的.</li>
<li>创建普通对象和创建数组所用的指令是不同的;前者用 new,后者用 newarray 等指令。</li>
<li>访问对象的成员变量和数组的元素不同，前者使用的是 getfield 指令，后者使用的是 aload 指令。</li>
<li>数组的类名和其它类也不同，数组的类名是用左括号+数组元素的类型描述符。同时，数组的类名和数组的类型描述符是一样的。eg：int[]的类名为：[I；int[][] 的类名为：[[I；String[][] 的类名为： [[java/lang/String；</li>
</ul>
<h1 id="数组的创建"><a href="#数组的创建" class="headerlink" title="数组的创建"></a>数组的创建</h1><p>普通类和数组类的创建方式不同,但是其归根结底还是 Object 的子类。所以要在之前的 Zclass 中添加额外的针对创建数组 class 的方法。同样由数组的 class 创建的数组 Object 和普通 Object 不同。所以还要在 Object 中添加额外的方法来创建数组 Object。可是不管数组类和普通类有什么区别，整体的流程都是一样的，凡是创建对象,都是使用 newXXX 的指令,通过对应的指令先创建其对应的 class,然后用该 class 来创建 object。<br>接下来依次从加载数组类，然后根据数组类创建数组对象的流程，讲解数组的创建过程。</p>
<h2 id="加载数组类"><a href="#加载数组类" class="headerlink" title="加载数组类"></a>加载数组类</h2><p>加载数组类和加载普通类的时机都是一样的，如果在 java 代码中显式的 new 了一个数组，那么势必会触发对应数组类的加载，而创建数组类的指令有三个：</p>
<ul>
<li>newarray：用于创建基本类型的一维数组，其操作数为一字节，该字节用来表示对应的基本类型</li>
<li>anewarray：用于创建引用类型的一维数组，其操作数为 2 字节，指向运行时常量池的一个类引用，该引用的类型就是引用类型数组中的元素类型</li>
<li>multianewarray：用于创建多维数组，其操作数为 3 字节，前两个字节同 anewarray，后一个字节用来表示多维数组的纬度，由此也可以看出我们在 Java 中创建多维数组最大纬度为 255。</li>
</ul>
<p>这里以 newarray 指令为例，查看其数组类加载的过程：<br>前面也说了 newarray 所创建的基本类型在指令后的字节中，JVM 为基本类型设置了对应的值，我们可以根据值来加载对应的类</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">int</span> AT_BOOLEAN = <span class="number">4</span>;</span><br><span class="line"><span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">int</span> AT_CHAR = <span class="number">5</span>;</span><br><span class="line"><span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">int</span> AT_FLOAT = <span class="number">6</span>;</span><br><span class="line"><span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">int</span> AT_DOUBLE = <span class="number">7</span>;</span><br><span class="line"><span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">int</span> AT_BYTE = <span class="number">8</span>;</span><br><span class="line"><span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">int</span> AT_SHORT = <span class="number">9</span>;</span><br><span class="line"><span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">int</span> AT_INT = <span class="number">10</span>;</span><br><span class="line"><span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">int</span> AT_LONG = <span class="number">11</span>;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">switch</span> (<span class="keyword">this</span>.index) &#123;</span><br><span class="line">    <span class="keyword">case</span> AT_BOOLEAN:</span><br><span class="line">        <span class="keyword">return</span> loader.loadClass(<span class="string">"[Z"</span>);</span><br><span class="line">    <span class="keyword">case</span> AT_BYTE:</span><br><span class="line">        <span class="keyword">return</span> loader.loadClass(<span class="string">"[B"</span>);</span><br><span class="line">    <span class="keyword">case</span> AT_CHAR:</span><br><span class="line">        <span class="keyword">return</span> loader.loadClass(<span class="string">"[C"</span>);</span><br><span class="line">    <span class="keyword">case</span> AT_SHORT:</span><br><span class="line">        <span class="keyword">return</span> loader.loadClass(<span class="string">"[S"</span>);</span><br><span class="line">    <span class="keyword">case</span> AT_INT:</span><br><span class="line">        <span class="keyword">return</span> loader.loadClass(<span class="string">"[I"</span>);</span><br><span class="line">    <span class="keyword">case</span> AT_LONG:</span><br><span class="line">        <span class="keyword">return</span> loader.loadClass(<span class="string">"[J"</span>);</span><br><span class="line">    <span class="keyword">case</span> AT_FLOAT:</span><br><span class="line">        <span class="keyword">return</span> loader.loadClass(<span class="string">"[F"</span>);</span><br><span class="line">    <span class="keyword">case</span> AT_DOUBLE:</span><br><span class="line">        <span class="keyword">return</span> loader.loadClass(<span class="string">"[D"</span>);</span><br><span class="line">    <span class="keyword">default</span>:</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> RuntimeException(<span class="string">"Invalid atype!"</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>然后用类加载器去加载对应的类。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> Zclass <span class="title">loadClass</span><span class="params">(String name)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (map.containsKey(name)) &#123;</span><br><span class="line">        <span class="keyword">return</span> map.get(name);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    Zclass clazz;</span><br><span class="line">    <span class="keyword">if</span> (name.charAt(<span class="number">0</span>) == <span class="string">'['</span>) &#123;</span><br><span class="line">        clazz = loadArrayClass(name);</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        clazz = loadNonArrayClass(name);</span><br><span class="line">    &#125;</span><br><span class="line">    ...</span><br><span class="line">    <span class="keyword">return</span> clazz;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="创建数组类"><a href="#创建数组类" class="headerlink" title="创建数组类"></a>创建数组类</h2><p>在加载对应的基本类型数组的时候，并不是从字节码文件中读取，然后转换为对应的 Class 对象，而是根据基本数组类型，直接创建对应的 class 对象。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> Zclass <span class="title">loadArrayClass</span><span class="params">(String name)</span> </span>&#123;</span><br><span class="line">    Zclass clazz = <span class="keyword">new</span> Zclass(AccessFlag.ACC_PUBLIC, name, <span class="keyword">this</span>, <span class="keyword">true</span>,</span><br><span class="line">            loadClass(<span class="string">"java/lang/Object"</span>),</span><br><span class="line">            <span class="keyword">new</span> Zclass[]&#123;loadClass(<span class="string">"java/lang/Cloneable"</span>), loadClass(<span class="string">"java/io/Serializable"</span>)&#125;);</span><br><span class="line">    map.put(name, clazz);</span><br><span class="line">    <span class="keyword">return</span> clazz;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>修改 Zclass ，我们之前创建 class 对象都是根据 class 文件，通过传入一个 ClassFile 对象构造 Class 对象的，而对于数组类型，我们为其添加一个构造方法，用来直接创建数组类型</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="title">Zclass</span><span class="params">(<span class="keyword">int</span> accessFlags, String thisClassName, ZclassLoader loader,</span></span></span><br><span class="line"><span class="function"><span class="params">              <span class="keyword">boolean</span> initStarted, Zclass superClass, Zclass[] interfaces)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">this</span>.accessFlags = accessFlags;</span><br><span class="line">    <span class="keyword">this</span>.thisClassName = thisClassName;</span><br><span class="line">    <span class="keyword">this</span>.loader = loader;</span><br><span class="line">    <span class="keyword">this</span>.initStarted = initStarted;</span><br><span class="line">    <span class="keyword">this</span>.superClass = superClass;</span><br><span class="line">    <span class="keyword">this</span>.interfaces = interfaces;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="创建数组对象"><a href="#创建数组对象" class="headerlink" title="创建数组对象"></a>创建数组对象</h2><p>上面创建的数组类型的 class 对象，那么接下来就该利用该 class 对象创建数组对象了，在 Zclass.java 中添加 newArray 方法。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> Zobject <span class="title">newArray</span><span class="params">(<span class="keyword">int</span> count)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (!isArray()) &#123;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> RuntimeException(<span class="string">"Not array class: "</span> + thisClassName);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">switch</span> (thisClassName) &#123;</span><br><span class="line">        <span class="keyword">case</span> <span class="string">"[Z"</span>:</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> Zobject(<span class="keyword">this</span>, <span class="keyword">new</span> <span class="keyword">byte</span>[count], <span class="keyword">null</span>);</span><br><span class="line">        <span class="keyword">case</span> <span class="string">"[B"</span>:</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> Zobject(<span class="keyword">this</span>, <span class="keyword">new</span> <span class="keyword">byte</span>[count], <span class="keyword">null</span>);</span><br><span class="line">        <span class="keyword">case</span> <span class="string">"[C"</span>:</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> Zobject(<span class="keyword">this</span>, <span class="keyword">new</span> <span class="keyword">char</span>[count], <span class="keyword">null</span>);</span><br><span class="line">        <span class="keyword">case</span> <span class="string">"[S"</span>:</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> Zobject(<span class="keyword">this</span>, <span class="keyword">new</span> <span class="keyword">short</span>[count], <span class="keyword">null</span>);</span><br><span class="line">        <span class="keyword">case</span> <span class="string">"[I"</span>:</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> Zobject(<span class="keyword">this</span>, <span class="keyword">new</span> <span class="keyword">int</span>[count], <span class="keyword">null</span>);</span><br><span class="line">        <span class="keyword">case</span> <span class="string">"[J"</span>:</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> Zobject(<span class="keyword">this</span>, <span class="keyword">new</span> <span class="keyword">long</span>[count], <span class="keyword">null</span>);</span><br><span class="line">        <span class="keyword">case</span> <span class="string">"[F"</span>:</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> Zobject(<span class="keyword">this</span>, <span class="keyword">new</span> <span class="keyword">float</span>[count], <span class="keyword">null</span>);</span><br><span class="line">        <span class="keyword">case</span> <span class="string">"[D"</span>:</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> Zobject(<span class="keyword">this</span>, <span class="keyword">new</span> <span class="keyword">double</span>[count], <span class="keyword">null</span>);</span><br><span class="line">        <span class="keyword">default</span>:</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> Zobject(<span class="keyword">this</span>, <span class="keyword">new</span> Zobject[count], <span class="keyword">null</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>该方法需要得到数组的大小，在 java 中所创建的数组时是需要确定其具体大小的，该值保存在执行创建数组的 frame 中的操作数栈中。同时在创建对象时，根据 thisClassName 确定具体的类型，然后创建具体的 obj。</p>
<p>同时注意到我们在创建 obj 对象时，是将创建好的数组赋值给了 Zobject 的 data 成员。该 data 成员在还没有介绍数组之前，是一个 slot[] 类型,用来保存非数组对象中的非静态成员变量,包含父类+ 自己的，现在引入了数组类型，需要将 Zobject 中的 data 类型做一个修改，这里直接改为 Object 类型，就可以做到既能盛放 slot，又能盛放数组对象。只不过在对普通对象和数组对象做元素存取的时候还要再进行强制类型转换，才能得到正确的值。其实我们可以这样理解，数组对象也是一个对象，只不过其内部的成员变量就是其数组的所有元素而已。</p>
<h2 id="创建基本类型数组的指令-newarray-执行过程"><a href="#创建基本类型数组的指令-newarray-执行过程" class="headerlink" title="创建基本类型数组的指令 newarray 执行过程"></a>创建基本类型数组的指令 newarray 执行过程</h2><p>其实前面已经将基本类型数组对象的创建过程进行了一次描述了，这里只是贴出该指令执行的代码，作为回顾。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">NEW_ARRAY</span> <span class="keyword">extends</span> <span class="title">Index8Instruction</span> </span>&#123;</span><br><span class="line">    <span class="comment">//Array Type  atype</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">int</span> AT_BOOLEAN = <span class="number">4</span>;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">int</span> AT_CHAR = <span class="number">5</span>;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">int</span> AT_FLOAT = <span class="number">6</span>;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">int</span> AT_DOUBLE = <span class="number">7</span>;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">int</span> AT_BYTE = <span class="number">8</span>;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">int</span> AT_SHORT = <span class="number">9</span>;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">int</span> AT_INT = <span class="number">10</span>;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">int</span> AT_LONG = <span class="number">11</span>;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">execute</span><span class="params">(Zframe frame)</span> </span>&#123;</span><br><span class="line">        OperandStack operandStack = frame.getOperandStack();</span><br><span class="line">        <span class="comment">//从栈中获取数组的大小</span></span><br><span class="line">        <span class="keyword">int</span> count = operandStack.popInt();</span><br><span class="line">        <span class="keyword">if</span> (count &lt; <span class="number">0</span>) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> NegativeArraySizeException(<span class="string">""</span> + count);</span><br><span class="line">        &#125;</span><br><span class="line">        ZclassLoader loader = frame.getMethod().getClazz().getLoader();</span><br><span class="line">        Zclass arrClazz = getPrimitiveArrayClass(loader);</span><br><span class="line">        Zobject arr = arrClazz.newArray(count);</span><br><span class="line">        operandStack.pushRef(arr);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//获取基本类型数组的 class;如果没有加载过,需要加载进 JVM</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> Zclass <span class="title">getPrimitiveArrayClass</span><span class="params">(ZclassLoader loader)</span> </span>&#123;</span><br><span class="line">        <span class="comment">//从字节码中获取到的 index 表明的是哪种类型的数组</span></span><br><span class="line">        <span class="keyword">switch</span> (<span class="keyword">this</span>.index) &#123;</span><br><span class="line">            <span class="keyword">case</span> AT_BOOLEAN:</span><br><span class="line">                <span class="keyword">return</span> loader.loadClass(<span class="string">"[Z"</span>);</span><br><span class="line">            <span class="keyword">case</span> AT_BYTE:</span><br><span class="line">                <span class="keyword">return</span> loader.loadClass(<span class="string">"[B"</span>);</span><br><span class="line">            <span class="keyword">case</span> AT_CHAR:</span><br><span class="line">                <span class="keyword">return</span> loader.loadClass(<span class="string">"[C"</span>);</span><br><span class="line">            <span class="keyword">case</span> AT_SHORT:</span><br><span class="line">                <span class="keyword">return</span> loader.loadClass(<span class="string">"[S"</span>);</span><br><span class="line">            <span class="keyword">case</span> AT_INT:</span><br><span class="line">                <span class="keyword">return</span> loader.loadClass(<span class="string">"[I"</span>);</span><br><span class="line">            <span class="keyword">case</span> AT_LONG:</span><br><span class="line">                <span class="keyword">return</span> loader.loadClass(<span class="string">"[J"</span>);</span><br><span class="line">            <span class="keyword">case</span> AT_FLOAT:</span><br><span class="line">                <span class="keyword">return</span> loader.loadClass(<span class="string">"[F"</span>);</span><br><span class="line">            <span class="keyword">case</span> AT_DOUBLE:</span><br><span class="line">                <span class="keyword">return</span> loader.loadClass(<span class="string">"[D"</span>);</span><br><span class="line">            <span class="keyword">default</span>:</span><br><span class="line">                <span class="keyword">throw</span> <span class="keyword">new</span> RuntimeException(<span class="string">"Invalid atype!"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h1 id="完善数组相关的其它指令"><a href="#完善数组相关的其它指令" class="headerlink" title="完善数组相关的其它指令"></a>完善数组相关的其它指令</h1><p>前面介绍了创建基本类型的数组指令 newarray，其实还有其它和数组相关的指令，这里做一个概述，具体实现请参考<a href="https://github.com/zachaxy/JVM/tree/master/Java/src/instructions/references" target="_blank" rel="noopener">instructions/references 包下的源码</a></p>
<h2 id="anewarray"><a href="#anewarray" class="headerlink" title="anewarray"></a>anewarray</h2><p>创建引用类型的一维数组。其过程和创建基本类型的一维数组是类似的，只不过该数组的元素是引用类型，所以我们要先获取到数组元素的引用类型。由 anewarray 指令后的操作数获取，其操作数为 2 字节，指向运行时常量池的一个类引用，该引用的类型就是引用类型数组中的元素类型。我们在获取到该类引用之后，先将其转换为直接引用(若还为加载过该类，则需要先加载到方法区)。接下来根据类型名，创建其一维数组名，eg：数组元素为 String，那么其一维数组类型名就是：[java/lang/String；接下来创建引用类型的一维数组的过程就和创建基本类型的一维数组过程就一样了。</p>
<h2 id="arraylength"><a href="#arraylength" class="headerlink" title="arraylength"></a>arraylength</h2><p>获取数组的长度，在 java 中也是很常用的，其实现也很简单，我们之间在创建数组对象的时候，将数组放到了 Zobject 的 data 变量中，我们可以通过 data 的 class 来获取原本数组类型名，根据类型名将 data 进行相应的类型转换，得到具体的数组之后，在获取其长度。</p>
<h2 id="aload-和-astore"><a href="#aload-和-astore" class="headerlink" title="aload 和 astore"></a><t>aload 和 <t>astore</t></t></h2><p>分别用来读取和写入数组元素，功能和之前介绍的 load，store 指令相似，只不过需要从操作数栈获取数组的索引，然后在对数组中对应的操作。比较简单，直接看代码，这里不再赘述了。<br>其实现分别在<code>instructions.loads.loadxarr</code>包下和<code>instructions.stores.storexarr</code>包下。</p>
<h2 id="multianewarray"><a href="#multianewarray" class="headerlink" title="multianewarray"></a>multianewarray</h2><p>这里以<code>new int[3][4][5]</code>为例，讲解多维数组的创建过程，具体实现过程，请参考<a href="https://github.com/zachaxy/JVM/tree/master/Java/src/instructions/references/MULTI_ANEW_ARRAY.java" target="_blank" rel="noopener">MULTI_ANEW_ARRAY.java</a><br>代码 <code>int[][][] arr = new int[3][4][5];</code><br>其产生的字节码为：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">iconst_3</span><br><span class="line">iconst_4</span><br><span class="line">iconst_5</span><br><span class="line">multianewarray #5 ([[[I,3)</span><br></pre></td></tr></table></figure>

<p>首先将三维数组各个维度压入操作数栈，栈顶向下一次为： 5，4，3，然后执行 multianewarray 指令，其操作数有两个，第一个 index 表示运行时常量池的类符号引用，其类名为[[[I<br>接着获取第二个操作数 3，表明这是一个三维数组。<br>接下来开始执行 multianewarray 指令：首先将获取到的类符号引用转为直接引用：转换依然是用 classloader，因为是数组类，所以不用从 class 文件中读取字节流，而是直接创建一个 class，该 class 将类名指定为 [[[I，这一创建 Class 对象的过程和创建一维数组是一样的；接下来依次从操作数栈中弹出三个整数，表示该多维数组每一维的大小；然后开始创建该多维数组的对象</p>
<p>多维数组对象的创建过程：此时拿到的类名是：[[[I，各个维的大小是 3，4，5；<br>首先利用数组类[[[I,创建第一维 arr1 ，大小为 3，（多维数组对外表现的就是一维数组，只不过该数组中的元素依然是数组。）<br>接下来创建 arr1 中的每一个元素，其元素也是数组，我们称之为第 2 维，arr2（arr1 中的三个元素都是 arr2）<br>arr2 此时的类型为 [[I，依然需要用 classloader 进行加载，然后创建；<br>接下来创建 arr2 中的每一个元素，其元素还是数组，我们称之为第 3 维，arr3（arr2 中的三个元素都是 arr3）<br>arr3 此时的类型为 [I,依然需要用 classloader 进行加载，然后创建；<br>最终将创建好的 arr1，压入操作数栈，结束！</p>
<h1 id="测试"><a href="#测试" class="headerlink" title="测试"></a>测试</h1><p>本节的测试代码在(TestNewArray09.java 中)[<a href="https://github.com/zachaxy/JVM/blob/master/Java/src/test/TestNewArray09.java]。" target="_blank" rel="noopener">https://github.com/zachaxy/JVM/blob/master/Java/src/test/TestNewArray09.java]。</a></p>


    </div>









      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    zachaxy
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="https://zachaxy.github.io/2018/01/12/手写JVM系列-14-数组的实现/" title="手写JVM系列(14)-数组的实现">https://zachaxy.github.io/2018/01/12/手写JVM系列-14-数组的实现/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>


    <footer class="post-footer">

        <div class="post-tags">

            <a href="/tags/JVM/" rel="tag"># JVM</a>

        </div>







        <div class="post-nav">
          <div class="post-nav-next post-nav-item">

              <a href="/2018/01/10/JNI开发流程/" rel="next" title="JNI开发流程">
                <i class="fa fa-chevron-left"></i> JNI开发流程
              </a>

          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">

              <a href="/2018/01/15/理解各种字符编码/" rel="prev" title="理解各种字符编码">
                理解各种字符编码 <i class="fa fa-chevron-right"></i>
              </a>

          </div>
        </div>




    </footer>
  </div>



  </article>



    <div class="post-spread">

    </div>
  </div>


          </div>









        </div>



  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">

      <div id="sidebar-dimmer"></div>

    <div class="sidebar-inner">




        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>


      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">

              <img class="site-author-image" itemprop="image" src="/images/avatar.jpg" alt="zachaxy">

              <p class="site-author-name" itemprop="name">zachaxy</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">


              <div class="site-state-item site-state-posts">

                <a href="/archives">

                  <span class="site-state-item-count">64</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>







              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">12</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>


          </nav>



          <div class="links-of-author motion-element">


                <span class="links-of-author-item">
                  <a href="https://github.com/zachaxy" target="_blank" title="GitHub">

                      <i class="fa fa-fw fa-globe"></i>GitHub</a>
                </span>

                <span class="links-of-author-item">
                  <a href="https://weibo.com/3242765540" target="_blank" title="Weibo">

                      <i class="fa fa-fw fa-globe"></i>Weibo</a>
                </span>


          </div>









        </div>
      </section>


      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">






              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#数组概述"><span class="nav-number">1.</span> <span class="nav-text">数组概述</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#数组的创建"><span class="nav-number">2.</span> <span class="nav-text">数组的创建</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#加载数组类"><span class="nav-number">2.1.</span> <span class="nav-text">加载数组类</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#创建数组类"><span class="nav-number">2.2.</span> <span class="nav-text">创建数组类</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#创建数组对象"><span class="nav-number">2.3.</span> <span class="nav-text">创建数组对象</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#创建基本类型数组的指令-newarray-执行过程"><span class="nav-number">2.4.</span> <span class="nav-text">创建基本类型数组的指令 newarray 执行过程</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#完善数组相关的其它指令"><span class="nav-number">3.</span> <span class="nav-text">完善数组相关的其它指令</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#anewarray"><span class="nav-number">3.1.</span> <span class="nav-text">anewarray</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#arraylength"><span class="nav-number">3.2.</span> <span class="nav-text">arraylength</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#aload-和-astore"><span class="nav-number">3.3.</span> <span class="nav-text">aload 和 astore</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#multianewarray"><span class="nav-number">3.4.</span> <span class="nav-text">multianewarray</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#测试"><span class="nav-number">4.</span> <span class="nav-text">测试</span></a></li></ol></div>


          </div>
        </section>
      <!--/noindex-->




    </div>
  </aside>



      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">zachaxy</span>


    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>

      <span class="post-meta-item-text">站点文章字数总计&#58;</span>

    <span title="站点文章字数总计">147.9k</span>

</div>






  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a></div>













      </div>
    </footer>


      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>

          <span id="scrollpercent"><span>0</span>%</span>

      </div>




  </div>



<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>
























    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>




    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>




    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>




    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>




    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>




    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>






  <script type="text/javascript" src="/js/src/utils.js?v=5.1.3"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.3"></script>







  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.3"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.3"></script>






  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.3"></script>







































  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>

















  <script type="text/javascript" src="/js/src/js.cookie.js?v=5.1.3"></script>
  <script type="text/javascript" src="/js/src/scroll-cookie.js?v=5.1.3"></script>





</body>
</html>
